import React, { useRef, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import { Button, Space, Tooltip, Slider } from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  FullscreenOutlined
} from '@ant-design/icons';
import * as d3 from 'd3';
import { getGraphTypeStyle, getLayoutStyle } from '../../styles/graphThemes';
import { 
  renderMindMap, 
  renderConceptMap, 
  renderFlowChart, 
  renderSocialNetwork, 
  renderOntologyGraph, 
  renderDefaultGraph 
} from '../../utils/graphRenderers';

/**
 * 专业图谱可视化组件
 * 支持多种图谱类型和布局方式的可视化
 */
const SpecializedGraphVisualization = forwardRef(({ 
  nodes = [], 
  edges = [], 
  graphType = 'knowledge',
  layout = 'force', 
  onLayoutChange,
  onNodeClick,
  onEdgeClick,
  onNodePositionUpdate,
  editable = false,
  width = '100%',
  height = 500,
  zoom = 1,
  animationSpeed = 0.3,
  isSimulationRunning: externalSimulationState,
  isFullscreen = false,
  onToggleFullscreen
}, ref) => {
  const svgRef = useRef(null);
  const containerRef = useRef(null);
  const simulationRef = useRef(null);
  
  const [currentZoom, setCurrentZoom] = useState(zoom);
  const [isSimulationRunning, setIsSimulationRunning] = useState(externalSimulationState !== undefined ? externalSimulationState : true);
  const [layoutSettings, setLayoutSettings] = useState({
    linkDistance: 100,
    linkStrength: 0.5,
    chargeStrength: -300,
    centerStrength: 0.1,
    collisionRadius: 30
  });

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    // 居中图谱
    centerGraph: () => {
      if (!svgRef.current) return;
      
      const svg = d3.select(svgRef.current);
      const containerWidth = containerRef.current?.clientWidth || 800;
      const containerHeight = containerRef.current?.clientHeight || 500;
      
      // 创建平滑的过渡动画
      svg.transition()
        .duration(750)
        .call(
          d3.zoom().transform,
          d3.zoomIdentity
            .translate(containerWidth / 2, containerHeight / 2)
            .scale(currentZoom)
        );
    },
    
    // 开始动画
    startSimulation: (speed) => {
      if (simulationRef.current) {
        simulationRef.current.alphaTarget(speed || animationSpeed).restart();
        setIsSimulationRunning(true);
      }
    },
    
    // 暂停动画
    pauseSimulation: () => {
      if (simulationRef.current) {
        simulationRef.current.alphaTarget(0).stop();
        setIsSimulationRunning(false);
      }
    },
    
    // 更新动画速度
    updateAnimationSpeed: (speed) => {
      if (simulationRef.current && isSimulationRunning) {
        simulationRef.current.alphaTarget(speed).restart();
      }
    },
    
    // 更新布局
    updateLayout: (newLayout, newLayoutConfig) => {
      console.log('🔧 SpecializedGraphVisualization 接收到布局更新:', newLayout, newLayoutConfig);
      // 强制重新渲染
      if (svgRef.current && nodes.length > 0) {
        // 触发重新渲染的方法
        setLayoutSettings(prev => ({ ...prev, ...newLayoutConfig }));
      }
    }
  }));

  // 主渲染函数
  useEffect(() => {
    console.log('🔍 SpecializedGraphVisualization useEffect 触发:', { 
      hasSvgRef: !!svgRef.current, 
      hasNodes: !!nodes, 
      nodesLength: nodes?.length || 0,
      layout, 
      graphType 
    });
    
    if (!svgRef.current || !nodes || nodes.length === 0) {
      console.log('❌ SpecializedGraphVisualization 渲染条件不满足');
      return;
    }

    console.log('✅ SpecializedGraphVisualization 开始重新渲染:', { layout, graphType, nodesCount: nodes.length });

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const container = svg.append('g').attr('class', 'container');
    
    // 创建缩放行为
    const zoomBehavior = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        // 使用安全的转换字符串格式，避免"Trailing garbage"警告
        const transform = event.transform;
        container.attr('transform', `translate(${transform.x}, ${transform.y}) scale(${transform.k})`);
        setCurrentZoom(transform.k);
      });

    svg.call(zoomBehavior);
    
    // 使用安全的初始化转换
    const initialTransform = d3.zoomIdentity.scale(currentZoom);
    svg.call(zoomBehavior.transform, initialTransform);

    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;

    let simulation;

    // 设置背景色
    const graphStyle = getGraphTypeStyle(graphType);
    if (graphStyle.background) {
      svg.style('background', graphStyle.background);
    }

    // 确保节点和边数据有效
    const validNodes = nodes.filter(node => node && node.id);
    const validEdges = edges.filter(edge => 
      edge && edge.source && edge.target && 
      validNodes.some(n => n.id === (typeof edge.source === 'object' ? edge.source.id : edge.source)) &&
      validNodes.some(n => n.id === (typeof edge.target === 'object' ? edge.target.id : edge.target))
    );

    // 根据图谱类型选择专门的渲染函数
    try {
      console.log('🎨 选择渲染函数，图谱类型:', graphType, '布局:', layout);
      
      switch (graphType) {
        case 'mind':
          console.log('🧠 使用思维导图渲染器');
          renderMindMap(container, validNodes, validEdges, containerWidth, containerHeight, onNodeClick);
          break;
        case 'concept':
        case 'causal':
          console.log('💡 使用概念图谱渲染器');
          simulation = renderConceptMap(container, validNodes, validEdges, containerWidth, containerHeight, onNodeClick, editable, onNodePositionUpdate);
          simulationRef.current = simulation;
          setIsSimulationRunning(true);
          break;
        case 'flow':
          console.log('📊 使用流程图渲染器');
          renderFlowChart(container, validNodes, validEdges, containerWidth, containerHeight, onNodeClick);
          break;
        case 'social':
          console.log('👥 使用社交网络渲染器');
          simulation = renderSocialNetwork(container, validNodes, validEdges, containerWidth, containerHeight, onNodeClick, editable, onNodePositionUpdate);
          simulationRef.current = simulation;
          setIsSimulationRunning(true);
          break;
        case 'ontology':
        case 'knowledge':
          console.log('📚 使用本体/知识图谱渲染器，布局:', layout);
          simulation = renderOntologyGraph(
            container, 
            validNodes, 
            validEdges, 
            containerWidth, 
            containerHeight, 
            onNodeClick, 
            editable, 
            onNodePositionUpdate,
            layout,
            layoutSettings
          );
          if (simulation) {
            simulationRef.current = simulation;
            setIsSimulationRunning(true);
          }
          break;
        default:
          // 默认使用通用的布局系统
          console.log('🔧 使用默认布局渲染器:', { layout, graphType });
          simulation = renderDefaultGraph(
            container, 
            validNodes, 
            validEdges, 
            graphType, 
            layout, 
            onNodeClick, 
            editable, 
            onNodePositionUpdate, 
            containerWidth, 
            containerHeight, 
            layoutSettings
          );
          if (simulation) {
            simulationRef.current = simulation;
            setIsSimulationRunning(true);
          }
      }
    } catch (error) {
      console.error("图谱渲染错误:", error);
      // 渲染错误提示
      container.append("text")
        .attr("x", containerWidth / 2)
        .attr("y", containerHeight / 2)
        .attr("text-anchor", "middle")
        .attr("fill", "#f5222d")
        .text("图谱渲染失败，请检查数据格式");
    }

    if (simulation) {
      // 设置动画速度
      simulation.alphaTarget(isSimulationRunning ? animationSpeed : 0);
      
      if (!isSimulationRunning) {
        simulation.stop();
      }
      
      simulation.on('end', () => {
        if (externalSimulationState === undefined) {
          setIsSimulationRunning(false);
        }
      });
    }

    return () => {
      if (simulation) {
        simulation.stop();
      }
    };
  }, [nodes, edges, layout, graphType, layoutSettings, currentZoom, onNodeClick, onNodePositionUpdate, editable]);

  // 控制函数
  const handleZoomIn = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom * 1.2)
    );
    setCurrentZoom(prev => prev * 1.2);
  };

  const handleZoomOut = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom / 1.2)
    );
    setCurrentZoom(prev => prev / 1.2);
  };

  const handleReset = () => {
    const svg = d3.select(svgRef.current);
    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;
    
    // 创建平滑的过渡动画
    svg.transition()
      .duration(750)
      .call(
        d3.zoom().transform,
        d3.zoomIdentity
          .translate(containerWidth / 2, containerHeight / 2)
          .scale(1)
      );
    setCurrentZoom(1);
  };

  const toggleSimulation = () => {
    if (simulationRef.current) {
      if (isSimulationRunning) {
        simulationRef.current.alphaTarget(0).stop();
        setIsSimulationRunning(false);
      } else {
        // 使用动画速度参数
        simulationRef.current.alphaTarget(animationSpeed).restart();
        setIsSimulationRunning(true);
      }
    }
  };

  // 获取当前图谱类型的中文名称
  const getGraphTypeName = () => {
    const graphStyle = getGraphTypeStyle(graphType);
    return graphStyle.name || '知识图谱';
  };

  // 获取当前布局类型的中文名称
  const getLayoutName = () => {
    const layoutConfig = getLayoutStyle(layout);
    return layoutConfig.name || '力导向布局';
  };

  return (
    <div style={{ 
      position: 'relative', 
      width, 
      height, 
      border: '1px solid #d9d9d9', 
      borderRadius: '8px', 
      overflow: 'hidden',
      background: getGraphTypeStyle(graphType).background || '#fff'
    }}>

      {/* 布局设置面板 */}
      {['concept', 'social', 'ontology', 'knowledge', 'causal', 'network'].includes(graphType) && layout === 'force' && (
        <div style={{
          position: 'absolute',
          top: '8px',
          left: '8px',
          zIndex: 10,
          background: 'rgba(255, 255, 255, 0.95)',
          borderRadius: '6px',
          padding: '12px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          width: '200px'
        }}>
          <div style={{ fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>布局参数</div>
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <div>
              <div style={{ fontSize: '11px', marginBottom: '4px' }}>连接距离: {layoutSettings.linkDistance}</div>
              <Slider
                min={50}
                max={200}
                value={layoutSettings.linkDistance}
                onChange={(value) => setLayoutSettings(prev => ({ ...prev, linkDistance: value }))}
                size="small"
              />
            </div>
            <div>
              <div style={{ fontSize: '11px', marginBottom: '4px' }}>排斥力: {Math.abs(layoutSettings.chargeStrength)}</div>
              <Slider
                min={100}
                max={500}
                value={Math.abs(layoutSettings.chargeStrength)}
                onChange={(value) => setLayoutSettings(prev => ({ ...prev, chargeStrength: -value }))}
                size="small"
              />
            </div>
          </Space>
        </div>
      )}

      {/* 视图控制面板 - 右上角 */}
      <div style={{
        position: 'absolute',
        top: '8px',
        right: '8px',
        zIndex: 15,
        background: 'rgba(255, 255, 255, 0.95)',
        borderRadius: '6px',
        padding: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        border: '1px solid #e8e8e8'
      }}>
        <Space size="small">
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="重置视图">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
          </Tooltip>
          {['concept', 'social', 'ontology', 'knowledge', 'causal', 'network'].includes(graphType) && (
            <Tooltip title={isSimulationRunning ? '暂停动画' : '播放动画'}>
              <Button 
                size="small" 
                icon={isSimulationRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />} 
                onClick={toggleSimulation}
                type={isSimulationRunning ? 'default' : 'primary'}
              />
            </Tooltip>
          )}
          {onToggleFullscreen && (
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏显示'}>
              <Button 
                size="small" 
                icon={<FullscreenOutlined />} 
                onClick={onToggleFullscreen}
                type={isFullscreen ? 'primary' : 'default'}
              />
            </Tooltip>
          )}
        </Space>
      </div>

      {/* SVG 画布 */}
      <div ref={containerRef} style={{ width: '100%', height: '100%' }}>
        <svg
          ref={svgRef}
          width="100%"
          height="100%"
          style={{ display: 'block' }}
        />
      </div>

      {/* 状态指示器 */}
      <div style={{
        position: 'absolute',
        bottom: '8px',
        left: '8px',
        background: 'rgba(0,0,0,0.7)',
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px'
      }}>
        <Space size="small">
          {editable && (
            <>
              <span style={{ color: '#1677ff' }}>编辑模式</span>
              <span>|</span>
            </>
          )}
          <span>缩放: {Math.round(currentZoom * 100)}%</span>
          <span>|</span>
          <span>节点: {nodes.length}</span>
          <span>|</span>
          <span>边: {edges.length}</span>
          <span>|</span>
          <span>类型: {getGraphTypeName()}</span>
          <span>|</span>
          <span>布局: {getLayoutName()}</span>
          {['concept', 'social', 'ontology', 'knowledge', 'causal', 'network'].includes(graphType) && (
            <>
              <span>|</span>
              <span style={{ color: isSimulationRunning ? '#52c41a' : '#ff4d4f' }}>
                {isSimulationRunning ? '运行中' : '已停止'}
              </span>
            </>
          )}
        </Space>
      </div>
    </div>
  );
});

export default SpecializedGraphVisualization;
